<template>
  <div class="mt-picker-wrap mt-select-wrap mt-picker--{{disabled ? 'disabled' : 'inited'}}">
    <div
      class="mt-picker-trigger"
      @tap="onTrigger"
    >
      <block wx:if="{{!inner_value || inner_value.length < 1 || inner_value[0] < 0 || !labeltext}}">
        <div class="mt-picker__init"><slot name="initial"></slot></div>
      </block>
      <block wx:else>
        <div class="mt-picker__content">
          <block wx:if="{{useSlot}}"><slot></slot></block>
          <block wx:else>{{labeltext}}</block>
        </div>
      </block>
      <div class="mt-picker__action"></div>
    </div>

    <van-popup
      show="{{ showPopup }}"
      position="bottom"
      overlay="{{ true }}"
      @click-overlay="onClickOverlay"
      overlay-style="background-color: rgba(0,0,0, .3)"
    >
      <div class="ui-flex ui-items-center ui-justify-between mt-picker__control">
        <div class="mt-picker__btn mt-picker__cancel" @tap="onCancel">取消</div>
        <div class="mt-picker__btn mt-picker__confirm" @tap="onConfirm">确定</div>
      </div>
      <van-picker
          item-height="{{itemHeight}}"
          id="picker"
          columns="{{ inner_columns }}"
          value-key="label"
          @change="onChange"></van-picker>
    </van-popup>
  </div>
</template>

<script>

  const formEmitterBehavior = require('../../behaviors/emitter.behavior')
  const formELementBehavior = require('../../behaviors/form-element.behavior')

  function isEmpty(value) {
    return !value || value.length < 1 || value[0] < 0
  }

  export default {
    behaviors: [
      formEmitterBehavior,
      formELementBehavior
    ],
    relations: {
      '../mt-form-item/index': {
        type: 'ancestor', // 关联的目标节点应为祖先节点
        linked(v) {
          this.formItem = v
          // console.log('this.formItem', this.formItem)
        },
        unlinked() {
          this.formItem = null
        }
      }
    },
    observers: {
      'sModel': function (field) {
        // console.log('field', field, this.data.sModel)
        if (Array.isArray(this.data.columns)) {
          this.setNativeValue(this.data.sModel)
        }
      }
    },
    properties: {
      sModel: null,
      indicatorStyle: {
        type: String,
        value: 'height: 50px;'
      },
      pickerStyle: {
        type: String,
        value: 'width: 100%; height: 200px;'
      },
      useSlot: {
        type: Boolean,
        value: false,
      },
      itemHeight: {
        type: Number,
        value: 40
      },
      disabled: {
        type: Boolean,
        value: false,
      },
      columns: {
        type: null,
        value: null,
        observer(newVal) {
          let newValIsNull = (Object.prototype.toString.call(newVal) === '[object Null]')
          if (newValIsNull) {
            this.setData({
              inner_columns: []
            })
          } else {
            // console.log('columns', parsedValue)
            this.setData({
              inner_columns: newVal
            })
          }
          // console.log('columns', newVal, this.data.inner_columns)
        }
      },
      index: {
        type: null,
        value: null,
        observer(newVal) {
          let newValIsNull = (Object.prototype.toString.call(newVal) === '[object Null]')
          if (newValIsNull) {

          } else {
            if (this.data.columns && this.data.columns.length > 0) {
              let picker = this.selectComponent('#picker')
              if (picker) {
                picker.setColumnIndex(0, newVal)
                // let column1 = picker.getColumnValue(0)
                // console.d('multipicker', newVal, column1)
                this.setData({
                  tmp_value: [
                    newVal,
                  ]
                })
                wx.nextTick(() => {
                  this.setData({
                    inner_value: newVal,
                  })
                })
              }
            }
          }
        }
      },
      defaultIndex: {
        type: Number,
        value: -1
      }
    },
    data() {
      return {
        inner_columns: [],
        inner_value: [],
        tmp_value: [],
        showPopup: false,
        labeltext: '',
        formItem: null,
        pickerReady: false
      }
    },
    methods: {
      setNativeValue(val) {
        let picker = this.selectComponent('#picker')
        let index = this.data.columns.findIndex(v => {
          return v.value === val
        })
        console.log('setNativeValue', index)
        this.selectIndex(index, picker)
      },
      onPickerReady(e) {
        const { picker } = e.detail
        let index = this.data.columns.findIndex(v => {
          return v.value === this.data.sModel
        })
        console.log('onPickerReady', index, this.data.defaultIndex)
        this.setData({
          pickerReady: true
        })
        wx.nextTick(() => {
          // 如果找到默认值 就默认选中
          if (index > -1) {
            console.log('reloaded', index)
            this.selectIndex(index, picker)
            return
          }
          if (this.data.defaultIndex > -1) {
            console.log('defaultIndex', this.data.defaultIndex)
            this.selectIndex(this.data.defaultIndex, picker)
          }
        })
        this.$native.emit('pickerready', {
          picker, context: this
        })
      },
      onTrigger(e) {
        if (!this.data.disabled) {
          this.$native.emit('open-popup')
          this.setData({
            showPopup: true
          })
        }
      },
      selectIndex(index, picker) {
        // let picker = this.selectComponent('#picker')
        // console.log(picker, index)
        picker.setColumnIndex(0, index)
        let tmpValue = [
          index,
        ]
        wx.nextTick(() => {
          this.setData({
            tmp_value: tmpValue,
            inner_value: tmpValue,
            labeltext: this.getLabel(tmpValue),
          })
        })
      },
      setSelectedIndex(newVal, show) {
        if (show) {
          console.log('call setSelectedIndex', newVal)
        }
        let picker = this.selectComponent('#picker')
        this.selectIndex(newVal, picker)
      },
      onClickOverlay() {
        this.resetIndex()
        this.$native.emit('close-popup')
        wx.nextTick(() => {
          this.setData({
            showPopup: false
          })
        })
      },
      onCancel() {
        this.resetIndex()
        this.$native.emit('close-popup')
        wx.nextTick(() => {
          this.setData({
            showPopup: false
          })
        })
      },
      getLabel(value) {
        let columns1 = this.data.inner_columns
        if (columns1[value] && columns1[value].label) {
          return [
            columns1[value].label,
          ].join()
        }
        return ''
      },
      setLabel(value){
        this.setData({
          labeltext: this.getLabel(value)
        })
      },
      onConfirm() {
        if (this.data.tmp_value &&
            this.data.tmp_value.length > 0
        ) {
          // console.log('mt-select', 'inner_value', this.data.inner_value)
          let tmp_value = this.data.tmp_value
          let inner_value = this.data.inner_value
          if (this.data.tmp_value[0] < 0) {
            tmp_value = [0]
          }
          // 如果值不变 就不处理
          if (inner_value && tmp_value &&
            Array.isArray(inner_value) && Array.isArray(tmp_value) &&
            inner_value[0] === tmp_value[0]) {
            this.$native.emit('close-popup')
            this.setData({
              showPopup: false
            })
            return
          }

          this.$native.emit('close-popup')
          let d = {
            inner_value: tmp_value,
            labeltext: this.getLabel(tmp_value),
            showPopup: false
          }
          d.tmp_value = tmp_value
          this.setData(d)
          this.fireChange(tmp_value)
        } else {
          this.$native.emit('close-popup')
          // console.log(isEmpty(this.data.inner_value))
          if (isEmpty(this.data.inner_value)) {
            // console.log(columns1, columns2)
            this.setData({
              tmp_value: [0],
              inner_value: [0],
              labeltext: this.getLabel([0]),
              showPopup: false
            })
            this.fireChange([0])
          }
        }
      },
      fireChange(newVal) {
        console.log('mt-select', newVal)
        // this.mtLiveCall(newVal[0])
        let index = newVal[0]
        this.$native.emit('change', {
          value: index
        })
        this.callComponent(this.formItem, 'mtFormChange', [this.data.columns[index].value])
      },
      onChange(e) {
        const { picker, value, index } = e.detail;
        console.log(e.detail)
        // picker.setColumnValues(1, citys[values[0]]);
        this.setData({
          tmp_value: [index],
        })
        // console.log('mt-select', 'change', e.detail, index)
        // console.log(this.data.tmp_value)
        // this.$native.emit('live-change', {
        //   picker, value, index
        // })

        // this.callComponent(this.formItem, 'mtFormChange', [value.value])
      },
      resetIndex() {
        let picker = this.selectComponent('#picker')
        if (picker) {
          picker.setColumnIndex(0, this.data.inner_value)
        }
      }
    },
  }
</script>

<style lang="less">
  @import "../../app.component.less";
</style>
